package com.example.controller;

import com.example.util.Result;
import com.example.util.UploadUtil;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
public class UploadController {

    @RequestMapping("/fileUpload")
    public Result fileUpload(@RequestParam("file") MultipartFile multipartFile) {
        Map<String, String> result = new HashMap<>();
        try {
            //        输入流
            InputStream inputStream = multipartFile.getInputStream();
            //            获取文件名
            String fileName = multipartFile.getOriginalFilename();
            //            获取文件后缀
            String subFix = fileName.substring(fileName.lastIndexOf("."));
            //            生成新文件名
            String realName = UUID.randomUUID() + subFix;
            UploadUtil.filerUpload(realName, inputStream);
            return Result.success().put("url", "https://file-upload02.oss-cn-beijing.aliyuncs.com/" + realName);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error(e.getMessage());
        }
    }
}
